<template>
  <div>
    <span class="titleStr">采购申请信息</span>
    <el-progress :percentage="100"  :show-text="false"></el-progress>
    <span class="describe">
    </span>
    <br>

    <el-form :model="purchaseApply" :rules = "rules" ref="ruleForm" label-width="100px">
      <el-form-item label="申请编码">
        <el-input  placeholder="自动生成无需添加" :disabled="true" style="width: 80%"></el-input>
      </el-form-item>

      <div class="block">
        <span class="demonstration" props="purchaseApply.enterTime">选择申请日期</span>
        <el-date-picker
            v-model="purchaseApply.enterTime"
            type="date"
            placeholder="选择日期">
        </el-date-picker>
      </div>


      <div class="block">
        <span class="demonstration">到货需求日期</span>
        <el-date-picker
            v-model="purchaseApply.deliveryDemandTime"
            align="right"
            type="date"
            placeholder="选择日期"
            :picker-options="pickerOptions">
        </el-date-picker>
      </div>
      <!--选择入库仓库-->
      <el-form-item label="入库仓库">
        <el-select v-model="purchaseApply.warehouseId" placeholder="选择仓库">
          <el-option
              v-for="warehouse in warehouses"
              :key="'warehouse'+warehouse.id"
              :label="warehouse.name"
              :value="warehouse.id"
          />
        </el-select>
      </el-form-item>
      <!--选择申请人-->
      <el-radio-group v-model="purchaseApply.source">
        <el-radio :label="3" value="补货" style="color:red">补货</el-radio>
        <el-radio :label="6" value="库存预警">库存预警</el-radio>
        <el-radio :label="9" value="工单需求">工单需求</el-radio>
      </el-radio-group>

<!--      显示采购申请人-->
      <el-form-item label="采购申请人">
        <el-input v-model="selectedEmployeeName" :disabled="true" style="width: 80%"></el-input>
      </el-form-item>



    </el-form>
    <!--选择申请人-->
    <el-button type="text" @click="EmployeeForm = true">选择采购申请人</el-button>
    <el-dialog title="采购申请人" :visible.sync="EmployeeForm">
      <el-form :model="employee">
        <!-- 选择部门 -->
        <el-row style="margin-bottom: 20px">
          <el-col :span="8">
            <el-tree
                :data="companyDepartments"
                :props="defaultProps"
                @node-click="handleNodeClick"
            ></el-tree>
          </el-col>
          <el-col :span="8">
            <el-table :data="employees" style="width: 100%">
              <el-table-column prop="name" label="姓名">
                <template slot-scope="scope">
                  <div @click="handleSelectionChange(scope.row)">
                    <span>{{ scope.row.name }}</span>
                    <el-button>选择</el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
        <el-row style="margin-bottom: 20px">
          <el-col :span="8">
            <!--            员工-->
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="EmployeeForm = false">取 消</el-button>
        <el-button type="primary" @click="handleNodeClickConfirm">确 定</el-button>
      </div>
    </el-dialog>



    <el-row :gutter="10"  style="margin-top: 10px;"><b>采购产品明细</b></el-row>
    <el-form prop="purchaseProductDetails.purchaseProductDetails" :rules="rules" >
      <el-table
          :data="purchaseProductDetails.purchaseProductDetails"
          style="width: 100%"
          ref="purchaseProductDetails">
<!--        序号-->
        <el-table-column
            prop="id"
            label="序号"
            width="50"
            type="index"
            align="center"
            :index="(index) => index + 1"/>

<!--        产品选择-->
        <el-table-column
            label="选择产品"
            align="center">
          <template slot-scope="scope">
            <el-button type="text" @click="selectProduct=true">{{title}}</el-button>
            <el-dialog title="选择产品" :visible.sync="selectProduct">
              <el-table
                  ref="singleTable"
                  :data="purchaseProductDetails.procurementProducts"
                  highlight-current-row
                  @row-click="handleChooseProduct($event, scope.$index)">
                <el-table-column
                    type="index"
                    width="50">
                </el-table-column>
                <el-table-column
                    prop="supplier.supplierName"
                    label="供应商名称"
                    width="120">
                </el-table-column>
                <el-table-column
                    prop="productShow.productCode"
                    label="产品编码"
                    width="120">
                </el-table-column>
                <el-table-column
                    prop="productShow.productName"
                    label="产品名称"
                    width="120">
                </el-table-column>
                <el-table-column
                    prop="productShow.productBrand"
                    label="品牌"
                    width="120">
                </el-table-column>
                <el-table-column
                    prop="productShow.productModels"
                    label="规格型号"
                    width="120">
                </el-table-column>
                <el-table-column
                    prop="image"
                    label="产品图片"
                    width="120">
                  <template slot-scope="scope">
                    <img src="/manage/product/image/1" alt="Product Image">
                    <img :src="scope.row.image" alt="产品图片" style="width: 50px; height: 50px;" />
                  </template>
                </el-table-column>
                <el-table-column
                    prop="productUnitPrice"
                    label="标准单价/元"
                    width="120">
                </el-table-column>
                <el-table-column
                    prop="productPrice"
                    label="采购单价/元"
                    width="120">
                </el-table-column>
                <el-table-column
                    prop="discountRate"
                    label="折扣率"
                    width="120">
                </el-table-column>
              </el-table>
              <div style="margin-top: 20px">
                <el-button @click="confirmSelection">确认</el-button>
                <el-button @click="selectProduct = false">取消选择</el-button>
              </div>
            </el-dialog>
          </template>
        </el-table-column>

<!--        显示选择产品的名称-->
        <el-table-column prop="productName" label="名称" align="center">
        </el-table-column>

        <el-table-column prop="productCode" label="产品编码" align="center">
        </el-table-column>
        <!--        采购单价(含税)/元-->
        <el-table-column prop="productUnitPrice" label="采购单价(含税)/元" align="center">
        </el-table-column>
<!--        显示供应商-->
        <el-table-column prop="supplierName" label="供应商" align="center">
        </el-table-column>
<!--        输入采购的数量-->
        <el-table-column prop="purchaseNum" label="采购数量" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.purchaseNum" placeholder="请输入数量" @input="calculateTotalPrice(scope.row)"></el-input>
          </template>
        </el-table-column>

<!--选择是否寻求报价-->
        <el-table-column prop="quote" label="是否询问报价" align="center">
          <template #default="scope">
            <el-select v-model="scope.row.quote" placeholder="请选择">
              <el-option label="需要询报价" style="color: #00aaff" :value="1"></el-option>
              <el-option label="无需询报价" style="color: gold" :value="0"></el-option>
            </el-select>
          </template>
        </el-table-column>
<!--产品采购总价格-->
        <el-table-column prop="totalPrice" label="产品采购总价(含税)/元" align="center">
          <template #default="scope">
            {{ scope.row.totalPrice }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button type="danger" size="small" @click="deleteProductDetail(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
<!--      所有产品总价格-->


    </el-form>
    <div style="margin-top: 20px; text-align: right;">
      <strong>所有产品总价(含税)/元: {{ purchaseProductDetails.AllTotalPrice }}</strong>
    </div>

    <div>
      <el-button
          size="small" icon="el-icon-plus" @click="addProductDetail"
          style="width: 100px; margin-top: 20px; background-color: #fff">添加
      </el-button>
    </div>
      <el-button type="primary" @click="submitForm">提交申请</el-button>
  </div>
</template>
<script>import axios from "axios";
export default {
  computed:{
    index(){
      return index
    }
  },
  data(){
    return {
      title:"选择产品",
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now();
        },
      },
      currentProduct:null,
      //采购产品明细
      purchaseProductDetails:{

        procurementProducts: [
        ],

        purchaseNum:'',//采购需求数量
        quote:'',//是否询问报价
        AllTotalPrice:'',//总价格
        productSupplierId:'',
        purchaseProductDetails:[
          {
            productSupplierId:'',
            productName:'',//产品名称
            productCode:'',//产品编码
            supplierName:'',
            // 采购单价(含税)/元
            productUnitPrice:'',
            // 采购需求数量
            purchaseNum:'',
            //产品采购总价/元
            totalPrice:'',
          }
        ],
      },

      purchaseApply:{
        // 申请人id
        employeeId:'',
        //申请日期
        enterTime:'',
        // 入库仓库
        warehouseId:'',
        // 到货需求日期
        deliveryDemandTime:'',
        //需求类型
        source:'',
      },
      warehouses:[],
      //当前展示员工数据
      employees:[],
      // 所有员工数据
      allEmployees:[],
      // 采购产品明细表暂存
      purchaseProductDetailsList:{
      },
      selectedEmployeeName:'',//员工姓名
      //选择采购申请人
      employee:{
        //id
        id:'',
        //所属部门
        companyDepartmentId:'',
      },

      companyDepartments: [],
      defaultProps: {
        children: 'children', //子部门
        label: 'name' // 显示的字段名
      },
      supplierFormPrice:false,
      EmployeeForm:false,
      selectProduct:false,
      rules: {
        'purchaseApply.enterTime': [
          { required: true, message: '请选择申请日期', trigger: 'change' }
        ],
        'purchaseApply.deliveryDemandTime': [
          { required: true, message: '请选择到货需求日期', trigger: 'change' }
        ],
        'purchaseApply.warehouseId': [
          { required: true, message: '请选择入库仓库', trigger: 'change' }
        ],
        'purchaseApply.source': [
          { required: true, message: '请选择申请人', trigger: 'change' }
        ],
        'purchaseProductDetails.purchaseProductDetails': {
          purchaseNum: [
            { required: true, message: '请输入采购数量', trigger: 'blur' },
            { type: 'number', message: '请输入数字', trigger: 'blur' },
            { validator: (rule, value, callback) => {
                if (value < 0) {
                  callback(new Error('采购数量不能为负数'));
                } else {
                  callback();
                }
              }, trigger: 'blur' }
          ],
          productUnitPrice: [
            { required: true, message: '请输入采购单价', trigger: 'blur' },
            { type: 'number', message: '请输入数字', trigger: 'blur' }
          ],
          totalPrice: [
            { required: true, message: '请输入总价格', trigger: 'blur' },
            { type: 'number', message: '请输入数字', trigger: 'blur' }
          ]
        }
    }}
  },
  created() {
    this.getWarehouseList();
    this.getEmployeeList();
    this.getCompanyDepartmentList();
    this.getSupplierProductInfoList();
  },
  methods:{


//所有数据提交
    submitForm() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // 收集数据
          let formData = {
            purchaseApply: this.purchaseApply,
            purchaseProductDetails: this.purchaseProductDetails.purchaseProductDetails // 确保这是一个数组
          };
          console.log(formData);
          // 发送请求
          this.axios.post("manage/purchaseApply/add", formData)
              .then(response => {
                // 处理成功响应
                this.$message.success('提交成功');
                // 可以重置表单或跳转到其他页面
                this.resetForm();
              })
              .catch(error => {
                // 处理错误响应
                this.$message.error('提交失败，请检查数据');
                console.error(error);
              });
        } else {
          // 表单验证失败
          this.$message.error('请填写完整信息');
          return false;
        }
      });
    },
    resetForm() {
      this.$refs.ruleForm.resetFields();
      this.purchaseProductDetails.purchaseProductDetails = [];
      this.purchaseProductDetails.AllTotalPrice = 0;
    },

    handleSelectionChange(res) {
      if (res) {
        this.selectedEmployeeName = res.name;
        this.purchaseApply.employeeId = res.id;
        console.log(this.purchaseApply.employeeId )
        this.$forceUpdate();
      }
    },
    handleNodeClick(data) {
      this.getEmployeesByDepartmentId(data.id);
    },
    getEmployeesByDepartmentId(departmentId) {
      this.$axios.get("manage/employee/listByDepartmentId/"+departmentId)
          .then(response => {
            this.employees = response.data.data;
          })
    },
    handleNodeClickConfirm() {
      this.EmployeeForm = false;
    },

    //供应商产品信息表

    getSupplierProductInfoList(){
      this.$axios.get("/manage/productSupplier/SupplierProductList")
          .then(response=>{
            this.purchaseProductDetails.procurementProducts = response.data.data;
            console.log(this.purchaseProductDetails.procurementProducts)
          })
    },




    //显示仓库列表
    getWarehouseList(){
      this.$axios.get("manage/warehouse/list")
          .then(response=>{
            this.warehouses=response.data.data;
          })
    },
    setCurrent(row) {
      this.$refs.singleTable.setCurrentRow(row);
      this.selectProduct = false;
    },
    handleCurrentChange(val) {
      this.currentRow = val;
    },

    // 添加一条产品明细
    addProductDetail(){
      this.purchaseProductDetails.purchaseProductDetails.push({

      });
    },
    handleChooseProduct(row, index) {
      this.currentIndex = index; // 记录当前选中的行索引
      this.purchaseProductDetailsList = row;
    },

    // 记录数据添加到行
    confirmSelection() {
      if (this.currentIndex !== -1 && this.purchaseProductDetailsList && this.purchaseProductDetailsList.productShow && this.purchaseProductDetailsList.supplier) {
        const currentRow = this.purchaseProductDetails.purchaseProductDetails[this.currentIndex];
        currentRow.productSupplierId = this.purchaseProductDetailsList.id;
        currentRow.productName = this.purchaseProductDetailsList.productShow.productName;
        currentRow.productCode = this.purchaseProductDetailsList.productShow.productCode;
        currentRow.supplierName = this.purchaseProductDetailsList.supplier.supplierName;
        currentRow.productUnitPrice = this.purchaseProductDetailsList.productShow.productUnitPrice;
        this.purchaseProductDetails.productSupplierId=this.purchaseProductDetails.purchaseProductDetails.productSupplierId;
        // 如果需要更新其他字段，可以在这里继续添加
        this.calculateTotalPrice(currentRow);
      } else {
        console.error('选择失败');
      }
      this.selectProduct = false;
    },
    calculateTotalPrice(row) {
      if (row.purchaseNum && row.productUnitPrice) {
        row.totalPrice = row.purchaseNum * row.productUnitPrice;
      } else {
        row.totalPrice = '';
      }
      this.calculateAllTotalPrice();
    },

    calculateAllTotalPrice() {
      let total = 0;
      this.purchaseProductDetails.purchaseProductDetails.forEach(item => {
        if (item.totalPrice) {
          total += item.totalPrice;
        }
      });
      this.purchaseProductDetails.AllTotalPrice = total;
    },

    deleteProductDetail(index) {
      this.purchaseProductDetails.purchaseProductDetails.splice(index, 1);
      this.calculateAllTotalPrice();
    },




    //查询所有部门列表
    getCompanyDepartmentList(){
      this.$axios.get("manage/companyDepartment/list")
          .then(response=>{
            this.companyDepartments=response.data.data;
          })
    },
    //显示员工列表
    getEmployeeList(){
      this.$axios.get("manage/employee/list")
          .then(response=>{
            this.employees=response.data.data;
          })
    }
  }
}
</script>